/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 22:48:41
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-24 16:00:03
 * @FilePath: \vue3_nuxt_demo\server\api\note\index.get.ts
 * @Description: 获取用户文集下全部的文章
 */
import Joi from 'joi';
import { responseJson, getLoginUid } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/**
 * 1、判断用户是否登录
 * 2、已登录则获取用户文集下的文章
 */

export default defineEventHandler(
  async (event)=>{

    //获取用户id，判断是否登录
    const uid = getLoginUid(event);

    // 判断用户id
    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401,{
        success: false,
        msg: '请先登录'
      });
    }

    // 获取请求参数
    const query = await getQuery(event);

    //校验数据joi
    const schema = Joi.object({
        notebookId: Joi.number().required()
    });

    // 校验请求参数
    try {
      const value = await schema.validateAsync(query);
    }
    catch (error) {
      return responseJson(400,  {
        success: false,
        msg: '参数错误',
        error: error
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {

      // 请求体
      const {notebookId} = query;

      //查询文章和文集的关联表
      const [notebookRows] = await con.query(
        'SELECT `note_id` FROM `notebook_notes` WHERE `notebook_id`=?',
        [notebookId]
      );

      //查询文章
      if (notebookRows.length < 1){
        return  responseJson(0,{
          success: false,
          msg: '无数据',
          data: []
        })
      }

      //遍历文章id
      const noteIds = notebookRows.map((item: any) => {
        return item.note_id;
      });

      //查询文章表
      const [notesRows] = await con.query(
        'SELECT id,title FROM `notes` WHERE `uid`=? AND id IN (?) ORDER BY `id` DESC',
        [uid, noteIds]
      );

      // 响应体
      return  responseJson(200,{
        success: true,
        msg: '获取成功',
        data: notesRows
      });
    }
    catch (error){

      setResponseStatus(event,500);
      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }
})